package com.ruike.alisurface.ui.mainPage;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ruike.alisurface.Constant;
import com.ruike.alisurface.MyApplication;
import com.ruike.alisurface.R;
import com.ruike.alisurface.Serials.MsgEventBus;
import com.ruike.alisurface.base.BaseAty;
import com.ruike.alisurface.bean.advBean;
import com.ruike.alisurface.bean.rkAdBean;
import com.ruike.alisurface.http.MchApiHttp;
import com.ruike.alisurface.utils.AdvDialogUtils;
import com.ruike.alisurface.utils.BackMainUtils;
import com.ruike.alisurface.utils.BannerImageLoader;
import com.ruike.alisurface.utils.GlideImageLoader;
import com.ruike.alisurface.utils.ShareKey;
import com.tencent.liteav.basic.log.TXCLog;
import com.tencent.rtmp.ITXVodPlayListener;
import com.tencent.rtmp.TXLiveConstants;
import com.tencent.rtmp.TXVodPlayer;
import com.tencent.rtmp.ui.TXCloudVideoView;
import com.voodoo.lib_utils.FileUtils;
import com.voodoo.lib_utils.GsonUtils;
import com.voodoo.lib_utils.L;
import com.voodoo.lib_utils.ShareUtils;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Created by czb on 2020-04-08.
 * <p>
 * 广告视频轮播图页面  进行图片或视频的替换显示
 */

public class VedioAdvActivity extends BaseAty {

    @BindView(R.id.videoPlayer_cloudPlayer_view)
    TXCloudVideoView txCloudVideoView;
    @BindView(R.id.activityBanner_banner)
    Banner activityBannerBanner;
    @BindView(R.id.tv_Player_noVideoadv)
    TextView tvPlayerNoVideoadv;
    @BindView(R.id.go_login)
    View goLogin;
    @BindView(R.id.bt_up_vedio)
    Button btUpVedio;
    @BindView(R.id.bt_up_img)
    Button btUpImg;
    @BindView(R.id.bt_shuax)
    LinearLayout btShuax;
    @BindView(R.id.adv_hd_img)
    ImageView adv_hd_img;
    List<String> mImgs = new ArrayList<>();
    private ArrayList<String> imglist = new ArrayList();//图片集合
    private ArrayList<String> videoUrls = new ArrayList<>();//视频集合
    private TXVodPlayer mVodPlayer;//播放对象
    private int playIndex = 0;//播放下标
    int adv_type; //广告类型

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_vedio_adv;
    }

    @Override
    protected void initViews() {
        goLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                continuousClick();
            }
        });
    }

    @Override
    protected void initData() {
        adv_hd_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AdvDialogUtils.AliHuoDongDialog(VedioAdvActivity.this, mImgs);
            }
        });
    }

    rkAdBean rkAdBean;
    ArrayList<String> advList;

    @Override
    public void onSuccess(String requestUrl, String requestJsonStr) {
        super.onSuccess(requestUrl, requestJsonStr);
        if (requestUrl.endsWith("get_rk_ad")) {
            rkAdBean = GsonUtils.json2Model(requestJsonStr, rkAdBean.class);
            mImgs.clear();
            mImgs.add(rkAdBean.getData().getAlert_page());
            advList = new ArrayList<>();
            advList.add(rkAdBean.getData().getSale_banner());
            advList.add(rkAdBean.getData().getOutgoods_banner());
            advList.add(rkAdBean.getData().getAlert_page());
            startTopAdvFileService(Constant.topAdvpath, advList);
            return;
        }

        if (requestUrl.endsWith("getMchBanner")) {
            try {
                JSONObject jsonObject = new JSONObject(requestJsonStr);
                JSONObject data = jsonObject.getJSONObject("data");
                advJdStr = data.optString("banner1");
                L.i("JDBanner", advJdStr);
                if (!TextUtils.isEmpty(advJdStr)) {
                    if (adv_type == 0) {
                        advData();
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    public void onError(String requestUrl, String errorMsg) {
        super.onError(requestUrl, errorMsg);
        if (requestUrl.endsWith("get_rk_ad")) {
            ShareUtils.getInstance().putBoolean(ShareKey.GET_RK_AD, false);
            adv_hd_img.setVisibility(View.GONE);
            return;
        }
        if (requestUrl.endsWith("getMchBanner")) {
            advJdStr = null;
        }

    }

    boolean istype;//判断是图片还是视频

    protected void initDatas() {
        if (adv_type == 0) {
            istype = true;
            advData();
        } else if (adv_type == 1) {
            istype = false;
            vedioData();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        L.i("广告视频页==" + this.getClass().getName());
        MchApiHttp.getrk_ad(this);
        MchApiHttp.getMchBanner(this);
        adv_type = ShareUtils.getInstance().getInt(ShareKey.ADV_TYPE, Constant.ADV_TYPE_IMAGE);
        if (adv_type == 0) {
            activityBannerBanner.setVisibility(View.VISIBLE);
            tvPlayerNoVideoadv.setVisibility(View.GONE);
        } else if (adv_type == 1) {
            tvPlayerNoVideoadv.setVisibility(View.VISIBLE);
            activityBannerBanner.setVisibility(View.GONE);
        }
        initDatas();
    }

    @Override
    public void doEventBusResult(MsgEventBus msg) {
        if (msg.getType().equals("adv")) {
            resBanner();
            advData();

        } else if (msg.getType().equals("vedio")) {

            if (mVodPlayer != null) {
                mVodPlayer.pause();
                mVodPlayer.stopPlay(true);
            }
            vedioData();

        } else if (msg.getType().equals("adv_type")) {

            ShareUtils.getInstance().putInt(ShareKey.ADV_TYPE, Constant.ADV_TYPE_IMAGE);
            if (mVodPlayer != null) {
                mVodPlayer.pause();
                mVodPlayer.stopPlay(true);
            }
            activityBannerBanner.setVisibility(View.VISIBLE);
            tvPlayerNoVideoadv.setVisibility(View.GONE);
            advData();

        } else if (msg.getType().equals("vedio_type")) {

            ShareUtils.getInstance().putInt(ShareKey.ADV_TYPE, Constant.ADV_TYPE_VIDEO);
            activityBannerBanner.stopAutoPlay();
            tvPlayerNoVideoadv.setVisibility(View.VISIBLE);
            activityBannerBanner.setVisibility(View.GONE);
            vedioData();

        } else if (msg.getType().equals("adv_activity") && msg.getMessage().equals("跳转商品页")) {
            Intent intent = BackMainUtils.setActivity(getApplicationContext());
            startActivity(intent);
        }

        if (msg.getType().equals("topadv")) {
            if (rkAdBean.getData().getSale_banner().contains(msg.getMessage())) {
                ShareUtils.getInstance().putBoolean(ShareKey.GET_RK_AD, true);
                adv_hd_img.setVisibility(View.VISIBLE);
                File file = new File(Constant.topAdvpath, msg.getMessage());
                if (file.exists()) {
                    L.i("topadv--本地文件存在");
                    GlideImageLoader.loadImage(this, file.getAbsolutePath(), adv_hd_img);
                } else {
                    L.i("topadv--本地文件不存在");
                    GlideImageLoader.loadImage(this, advList.get(0), adv_hd_img);
                }
            }
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        resBanner();
        resPlay();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /**
     * 释放banner
     */
    public void resBanner() {
        if (activityBannerBanner != null) {
            activityBannerBanner.stopAutoPlay();
            activityBannerBanner.releaseBanner();
        }
    }

    /**
     * 释放播放器
     */
    public void resPlay() {
        if (mVodPlayer != null) {
            mVodPlayer.pause();
            mVodPlayer.stopPlay(true);
            txCloudVideoView.stop(true);
            txCloudVideoView.onDestroy();
        }
    }

    String advJdStr;

    /**
     * 添加要扶持的广告在首位
     *
     * @param
     */
    public void addJdAdv() {
        if (TextUtils.isEmpty(advJdStr)) {
            return;
        }
        if (imglist.size() > 1) {
            imglist.add(0, advJdStr);
        } else {
            imglist.add(advJdStr);
        }
    }

    private void setadvImg() {
        imglist.clear();
        addJdAdv();
        File[] folderFileList = FileUtils.getFolderFileList(Environment.getExternalStorageDirectory() + File.separator + "picture" + File.separator + "adv");

        for (File file : folderFileList) {
            if (file.getName().endsWith(".jpg") || file.getName().endsWith(".png") || file.getName().endsWith(".jpeg") || file.getName().endsWith(".gif")) {
                imglist.add(file.getPath());
            }
        }

        if (imglist.size() <= 0) {
            String Rd = "http://120.78.219.34:8018/UploadFile/ad/7fc9a4dc-5533-4419-a4ad-f243f35ae33d.jpg";
            imglist.add(Rd);
        }

    }

    private void setVedio() {
        videoUrls.clear();
        ArrayList<advBean> imgshop = (ArrayList<advBean>) MyApplication.finalDbUtils.findAllByWhere(advBean.class, " types = '1'");
        File[] folderFileList = FileUtils.getFolderFileList(Environment.getExternalStorageDirectory() + File.separator + "picture" + File.separator + "Vedio");
        for (File file : folderFileList) {
            if (file.getName().endsWith(".mp4")) {
                if (imgshop.size() > 0) {
                    for (advBean sbean : imgshop) {
                        if (sbean.getUrl().endsWith(file.getName())) {
                            videoUrls.add(file.getPath());
                            break;
                        }
                    }
                } else {
                    videoUrls.add(file.getPath());
                }
            }
        }
        if (videoUrls.size() <= 0) {
            for (File file : folderFileList) {
                if (file.getName().endsWith(".mp4")) {
                    videoUrls.add(file.getPath());
                }
            }
        }

    }

    /**
     * |图片数据的读取及展示
     */
    public void advData() {
        setadvImg();
        if (imglist.size() > 0) {
            tvPlayerNoVideoadv.setVisibility(View.GONE);
            activityBannerBanner.setIndicatorGravity(BannerConfig.CIRCLE_INDICATOR);

            // 设置图片加载器
            activityBannerBanner.setImageLoader(new BannerImageLoader());
            // 设置banner样式
            activityBannerBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
            // 设置图片集合
            activityBannerBanner.setImages(imglist);
            // 设置自动轮播，默认为true
            activityBannerBanner.isAutoPlay(true);
            // 设置轮播时间单位毫秒
            activityBannerBanner.setDelayTime(3000);
            activityBannerBanner.start();
        } else {
            tvPlayerNoVideoadv.setVisibility(View.VISIBLE);
            tvPlayerNoVideoadv.setText(getResources().getText(R.string.noAdvPleaseCopyStr));
        }
    }

    /**
     * 视频数据的读取及播放
     */
    public void vedioData() {
        setVedio();
        if (videoUrls.size() > 0) {
            tvPlayerNoVideoadv.setVisibility(View.GONE);
            // 创建 player 对象
            if (mVodPlayer == null) {
                txCloudVideoView.clearLog();
                txCloudVideoView.disableLog(true);
                txCloudVideoView.showLog(false);
                txCloudVideoView.showVideoDebugLog(0);
                mVodPlayer = new TXVodPlayer(this);
                mVodPlayer.setPlayerView(txCloudVideoView);
                TXCLog.setConsoleEnabled(false);
                TXCLog.setLevel(TXCLog.LOG_FATAL);
            }

            mVodPlayer.setRenderMode(TXLiveConstants.RENDER_MODE_ADJUST_RESOLUTION);//适应视频大小
//            mVodPlayer.setRenderMode(TXLiveConstants.RENDER_MODE_FULL_FILL_SCREEN);//全屏裁剪
            mVodPlayer.setVodListener(new ITXVodPlayListener() {
                @Override
                public void onPlayEvent(TXVodPlayer txVodPlayer, int event, Bundle param) {
                    // 播放完成
                    if (event == TXLiveConstants.PLAY_EVT_PLAY_END) {
                        playIndex++;
                        if (playIndex >= videoUrls.size()) {
                            playIndex = 0;
                        }

                        mVodPlayer.stopPlay(true);
                        String url = videoUrls.get(playIndex);

                        mVodPlayer.startPlay(url);
                        return;
                    }
                    // 播放进度
                    if (event == TXLiveConstants.PLAY_EVT_PLAY_PROGRESS) {
                        // 播放进度, 单位是毫秒
                        int progress_ms = param.getInt(TXLiveConstants.EVT_PLAY_PROGRESS_MS);
                        // 视频总长, 单位是毫秒
                        int durationCount_ms = param.getInt(TXLiveConstants.EVT_PLAY_DURATION_MS);
//                        timeTv.setText(new StringBuffer().append("视频时长：").append(durationCount_ms / 1000).append(" 播放进度：").append(progress_ms / 1000));
                    }
                }

                @Override
                public void onNetStatus(TXVodPlayer txVodPlayer, Bundle param) {
                }
            });
            // 刚开始设置列表中下标为0的文件
            mVodPlayer.startPlay(videoUrls.get(playIndex));
           /* txCloudVideoView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    LogUtils.i("点击了视频");
                }
            });*/
        } else {
            tvPlayerNoVideoadv.setVisibility(View.VISIBLE);
            tvPlayerNoVideoadv.setText(new StringBuffer().append("目录文件中没有视频文件").append("请到网页后台设置视频"));
        }
    }

    /**
     * 判断是否点击在该控件上
     *
     * @param view
     * @param ev
     * @return
     */
    public boolean inRangeOfView(View view, MotionEvent ev) {
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        int x = location[0];
        int y = location[1];
        return !(ev.getX() < x) && !(ev.getX() > (x + view.getWidth())) && !(ev.getY() < y) && !(ev.getY() > (y + view.getHeight()));
    }

    //判断是否操作当前页面，如果操作就重新计时，在跳转页面
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            //获取触摸动作，如果ACTION_UP，计时开始。
            case MotionEvent.ACTION_UP:
//                ALog.i(" 触摸动作 拿起");
                /*    || inRangeOfView(imageView, ev)*/
                if (inRangeOfView(btShuax, ev) || inRangeOfView(goLogin, ev)
                        || inRangeOfView(btUpImg, ev) || inRangeOfView(btUpVedio, ev) || inRangeOfView(adv_hd_img, ev)) {

                } else {
                    BackMainUtils.setActivity(this);
//                    finish();
                }
                break;
            //否则其他动作计时取消
            default:
                break;
        }
        return super.dispatchTouchEvent(ev);
    }

    public Bitmap getTxVedioBitmap() {
        return txCloudVideoView.getVideoView().getBitmap();
    }
}